import axios from "axios"
import { message } from "antd"
import store from '@/store' // store.dispatch()
import { resetUser } from '@/store/actions'

const baseURL = 'http://localhost:3000'
const version = '/api/v1'

const instance = axios.create({
  baseURL: baseURL + version,
  timeout: 5000,
  headers: {}
})

instance.interceptors.request.use(config => {
  // 添加headers，向后端传递token
  config.headers.Authorization = localStorage.getItem('token')
  return config
}, error => {
  return Promise.reject(error)
})

instance.interceptors.response.use(response => {
  if (response.data?.success) {
    return response.data.data
  }
  if (response.data.err === 0) {
    return response.data.data
  } else if (response.data.err === -1) {
    store.dispatch(resetUser())
    message.error('登录过期，请重新登录')
  } else {
    // 业务逻辑的失败，-1表示token过期，其他情况是业务错误
    return message.error(response.data.msg)
  }
  return response
}, error => {
  message.error('网络异常，请稍后重试')
  return Promise.reject(error)
})

export default instance